package com.planw.beetl.service;

import com.intellij.codeInsight.lookup.AutoCompletionPolicy;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiFile;
import com.intellij.psi.search.FilenameIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.ui.JBColor;
import com.intellij.util.PlatformIcons;
import com.planw.beetl.utils.StrUtil;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;

/**
 * beetlsql markdown 文件中相关操作的需要的方法
 */
public class BeetlSqlService {

  public static final Map<PsiFile, PsiClass> mapperCache = new ConcurrentHashMap<>();

  private static final Logger logger = Logger.getInstance(BeetlSqlService.class);

  private final Project project;

  public BeetlSqlService(Project project) {

    this.project = project;
  }

  public static BeetlSqlService getInstance(Project project) {

    return project.getService(BeetlSqlService.class);
  }

  /**
   * 通过markdown文件查找对应的BaseMapper。<br/> 必须符合：优先注解SqlResource，然后是泛型指定的实体类名
   *
   * @param mdFile
   *     markdown的PsiFile
   */
  public PsiClass findMapperClass(PsiFile mdFile) {

    if (mdFile == null) {
      return null;
    }
    BeetlMapperService beetlMapperService = BeetlMapperService.getInstance(this.project);
    Module module = ModuleUtil.findModuleForFile(mdFile.getOriginalFile());
    Collection<PsiClass> allMappers = beetlMapperService.getAllMappers(module);
    for (PsiClass mapperClass : allMappers) {
      String guessMdFilePath = beetlMapperService.guessMdFilePathByMapperClass(mapperClass);
      PsiFile guessMdFile = beetlMapperService.getBeetlSqlFile(module, guessMdFilePath);
      if (guessMdFile != null && guessMdFile.getOriginalFile()
          .isEquivalentTo(mdFile.getOriginalFile())) {
        return mapperClass;
      }
    }
    return null;
  }


}
